package com.steven.im.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.bumptech.glide.Glide;
import com.orhanobut.logger.Logger;
import com.steven.im.R;
import com.steven.im.base.BaseFragment;
import com.steven.im.base.Constant;
import com.steven.im.entity.AccountEntity;
import com.steven.im.entity.BaseEntity;
import com.steven.im.imageLoader.GlideImageLoader;
import com.steven.im.net.MyCallback;
import com.steven.im.net.Task;
import com.steven.im.ui.activity.ImLoginActivity;
import com.steven.im.ui.activity.LoginAndRegisterActivity;
import com.steven.im.ui.activity.MainActivity;
import com.steven.im.ui.activity.MyaddrActivity;
import com.steven.im.ui.activity.MycollectActivity;
import com.steven.im.ui.activity.MyorderActivity;
import com.steven.im.ui.activity.SettingActivity;
import com.steven.im.ui.activity.TransDetailsActivity;
import com.steven.im.ui.activity.WebActivity;
import com.steven.im.utils.GsonUtils;
import com.steven.im.utils.SPUtils;
import com.steven.im.utils.ScreenUtil;
import com.steven.im.utils.ToastUtil;
import com.steven.im.utils.UserUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Response;

/**
 * Created by Steven on 2019/1/4.
 * 个人中心
 */
public class AccountFragment extends BaseFragment {

    private static final String TAG = "AccountFragment";

    private boolean isFirst = true;//默认第一次加载
    @BindView(R.id.civ_head)
    CircleImageView civHead;
    @BindView(R.id.view_status_bar_place)
    View statusBarPlace;
    @BindView(R.id.tv_login)
    TextView tvLogin;//用户昵称

    //钱包部分容器(默认显示钱包)
    Banner mBanner;
    @BindView(R.id.rl_wallet)
    RelativeLayout rlWallet;

    //3个数值
    @BindView(R.id.tv_xingyun)
    TextView tvXingyun;
    @BindView(R.id.tv_zengsong)
    TextView tvZengsong;
    @BindView(R.id.tv_dikou)
    TextView tvDikou;

    String shareUrl = "";
    private String helpUrl = "";

    @SuppressLint("InflateParams")
    @Override
    public View setContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.account_fragment, null);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ViewGroup.LayoutParams params = statusBarPlace.getLayoutParams();
        params.height = ScreenUtil.getStatusBarHeight(getContext());
        statusBarPlace.setLayoutParams(params);
        mBanner = view.findViewById(R.id.banner);
        setListen();

    }

    private void setListen() {
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            isFirst = false;
//            initData();
            if (!UserUtils.checkLogin()) {
                startActivity(new Intent(getActivity(), ImLoginActivity.class));
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!isFirst) {
            //非首次启动并且JESSIONID不为空，获取用户账户信息
            if (!UserUtils.checkLogin()) {//用户未登录，到指定页
                int currentPos = ((MainActivity) getActivity()).getCurrentTab();
                ((MainActivity) getActivity()).getTabLayout().setCurrentTab(currentPos);
            } else {//已登录，刷新数据
                initData();
            }
        }
    }

    @OnClick({R.id.iv_setting, R.id.tv_mywallet, R.id.tv_waitpay, R.id.tv_waitreceive, R.id.tv_finish, R.id.tv_myorder,
            R.id.rl_mycollect, R.id.rl_myaddr, R.id.shareSoftware, R.id.help_center})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        if (!UserUtils.checkLogin()) {
            startActivity(new Intent(getActivity(), ImLoginActivity.class));
        }
        switch (view.getId()) {
            case R.id.tv_mywallet://我的钱包
                startActivity(new Intent(getActivity(), TransDetailsActivity.class));
                break;
            case R.id.iv_setting://设置
                startActivity(new Intent(getActivity(), SettingActivity.class));
                break;
            case R.id.tv_waitpay://待支付
                startActivity(new Intent(getActivity(), MyorderActivity.class)
                        .putExtra("status", 0));
                break;
            case R.id.tv_waitreceive://待收货
                startActivity(new Intent(getActivity(), MyorderActivity.class)
                        .putExtra("status", 1));
                break;
            case R.id.tv_finish://已完成
                startActivity(new Intent(getActivity(), MyorderActivity.class)
                        .putExtra("status", 2));
                break;
            case R.id.tv_myorder://我的订单
                startActivity(new Intent(getActivity(), MyorderActivity.class)
                        .putExtra("status", -1));
                break;
            case R.id.rl_mycollect://我的收藏
                startActivity(new Intent(getActivity(), MycollectActivity.class));
                break;
            case R.id.rl_myaddr://收货地址
                startActivity(new Intent(getActivity(), MyaddrActivity.class));
                break;
            case R.id.help_center:
                if (TextUtils.isEmpty(helpUrl)) {
                    return;
                }
                startActivity(new Intent(getActivity(), WebActivity.class)
                        .putExtra("url", helpUrl)
                        .putExtra("title", "帮助中心"));
                break;
            case R.id.shareSoftware://分享软件
                startActivity(new Intent(getActivity(), WebActivity.class)
                        .putExtra("url", shareUrl)
                        .putExtra("title", "好友邀请"));
                break;
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        //获取用户账户信息
        Task.getApiService().getMyAccount().enqueue(new MyCallback<BaseEntity>(getActivity()) {
            @Override
            public void onSuccess(Response<BaseEntity> response) {
                try {
                    if ("0".equals(response.body().getCode())) {
                        //获取我的账户信息成功
                        AccountEntity accountEntity = GsonUtils.parseJSON(response.body().getResult().toString(),
                                AccountEntity.class);
                        if (accountEntity != null) {
                            //刷新界面
                            updateView(accountEntity);
                            shareUrl = accountEntity.getShareUrl();
                            helpUrl = accountEntity.getHelpUrl();
                        }
                    } else {//登录失败
                        ToastUtil.showShort(getActivity(), response.body().getMessage());
                        UserUtils.clearUserInfo();
                        int currentPos = ((MainActivity) getActivity()).getCurrentTab();
                        ((MainActivity) getActivity()).getTabLayout().setCurrentTab(currentPos);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable t) {
            }
        });

    }


    /**
     * 刷新数据
     */
    private void updateView(AccountEntity accountEntity) {
        //保存个人信息
        SPUtils.put(getActivity().getApplicationContext(), Constant.UserInfo.ID, accountEntity.getUserId());
        SPUtils.put(getActivity().getApplicationContext(), Constant.UserInfo.NICKNAME, accountEntity.getUserNickname());

        //更新头像
        Glide.with(getActivity()).load(accountEntity.getUserAvatar())
                .into(civHead);

        //更新昵称
        if (TextUtils.isEmpty(accountEntity.getUserNickname())) {
            tvLogin.setText(accountEntity.getUserAccount());
        } else {
            tvLogin.setText(accountEntity.getUserNickname());
        }

        if (accountEntity.isBidding()) {//显示钱包
            mBanner.setVisibility(View.INVISIBLE);
            rlWallet.setVisibility(View.VISIBLE);
            //账户余额
            tvXingyun.setText(accountEntity.getBiddingCurrency());
            tvZengsong.setText(accountEntity.getGivingCurrency());
            tvDikou.setText(accountEntity.getShoppingCurrency());
        } else {//显示banner
            rlWallet.setVisibility(View.INVISIBLE);
            mBanner.setVisibility(View.VISIBLE);
            setBanner(accountEntity.getBannerList());
        }


    }

    /**
     * 设置banner图
     */
    private void setBanner(JSONArray bannerArray) {
        final List<String> titleList = new ArrayList<>();
        List<String> urlList = new ArrayList<>();
        final List<String> linkUrlList = new ArrayList<>();
        if (bannerArray != null && !bannerArray.isEmpty()) {
            try {
                for (int i = 0; i < bannerArray.size(); i++) {
                    titleList.add(bannerArray.getJSONObject(i).getString("title"));
                    urlList.add(bannerArray.getJSONObject(i).getString("url"));
                    linkUrlList.add(bannerArray.getJSONObject(i).getString("linkUrl"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //        //设置banner样式
        mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        mBanner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        mBanner.setImages(urlList);
        //设置banner动画效果
        mBanner.setBannerAnimation(Transformer.DepthPage);
        //设置自动轮播，默认为true
        mBanner.isAutoPlay(true);
        //设置轮播时间
        mBanner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        mBanner.setIndicatorGravity(BannerConfig.CENTER);
        mBanner.start();
        mBanner.startAutoPlay();
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                startActivity(new Intent(getActivity(), WebActivity.class).putExtra("title", titleList.get(position)).putExtra("url", linkUrlList.get(position)));
            }
        });
    }

}
